import AliyunOSSUpload from '@/components/AliyunOSSUpload';
import { add_edit_video } from '@/services/assrssment';
import { filedlist } from '@/services/platformuser';
import { get_acceass } from '@/utils/Aliyun_oss';
import { UploadOutlined } from '@ant-design/icons';
import {
  ActionType,
  ProColumns,
  ProForm,
  ProFormGroup,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { Button, Divider, message, Modal, Table, Upload } from 'antd';
import { RcFile } from 'antd/es/upload';
import moment from 'moment';
import { useState } from 'react';

interface Iprops {
  isShowAddVideoModal: (show: boolean) => void;
  addVideoModal: boolean;
  actionRef: React.MutableRefObject<ActionType | undefined>;
}
type GithubIssueItem = {
  video_name: string;
  id: number;
  video_times: number;
  size: number;
  time: string;
  zhiceng: string;
  plan_time: string;
  end_time: string;
  create_at: string;
  create_user: string;
};
var videname = '';
var sizes = '0';
const AddMyselfVideo = (props: Iprops) => {
  const { isShowAddVideoModal, addVideoModal, actionRef } = props;
  // 个人信息
  const { initialState } = useModel('@@initialState');
  // 视频时长
  const [video_time, setvideo_time] = useState(0);
  const [disable, setdisable] = useState(false);
  const [video, setvideo] = useState<any>([{}]);
  // 上传状态
  const [uploading, setuploading] = useState(false);
  // 图片地址
  const [imageUrl, setimageUrl] = useState('');
  // 视频地址
  const [videourl, setvideourl] = useState<any>();

  // 删除视频
  const Delvideo = () => {
    setdisable(false);
    setvideo([{}]);
    setvideo_time(0);
  };

  // 图片删除
  const del = () => {
    setimageUrl('');
  };

  // 获取视频分类
  const get_field = async (key: string) => {
    let request_body = {
      type: key,
    };
    let params = await filedlist(request_body);
    // console.log(params);
    let res: any = [];
    params.data.map((item: any) => {
      let temp: any = {};
      temp['label'] = item.value;
      temp['value'] = parseInt(item.key);
      res.push(temp);
    });
    return res;
  };

  //获取oss服务端签名
  const send_request = async (info: any) => {
    let res = await get_acceass(info);
    doUploadFile(res.ossHost, res.glo_image_data, res.filePath);
  };

  // 视频大小转换
  function sizeTostr(size: number) {
    //转化MB
    var data = (size / (1024 * 1024)).toFixed(2);
    var len = data.indexOf('.');
    var dec = data.substring(len + 1, 2);
    if (dec == '00') {
      //当小数点后为00时 去掉小数部分
      return data.substring(0, len) + data.substr(len + 3, 2);
    }
    return data;
  }

  function doUploadFile(
    url: string,
    data: { [x: string]: string | Blob; file: any },
    filePath: any,
  ) {
    setuploading(true);
    setdisable(true);

    var oMyForm = new FormData();
    for (var field_name in data) {
      oMyForm.append(field_name, data[field_name]);
    }
    var oReq = new XMLHttpRequest(); //上传结果
    oReq.onreadystatechange = function (e) {
      if (oReq.readyState == 4) {
        if (oReq.status == 200) {
          setvideourl(filePath);
          // 获取视频时长
          var audio = new Audio(filePath);
          audio.addEventListener('loadedmetadata', function (e) {
            setvideo_time(Math.round(audio.duration));
          });
          var myDate = new Date();
          let upload_time = myDate.toLocaleTimeString();
          let getuploadinfo: any = data.file;
          let resresults = [];
          let temp: any = {};
          // video_name  文件名称  video_times 视频时长  size 文件大小 name 上传人   upload_time 上传时间
          videname = getuploadinfo.name;
          console.log(getuploadinfo.name, getuploadinfo.size);
          sizes = sizeTostr(getuploadinfo.size);
          temp['video_name'] = getuploadinfo.name;
          temp['size'] = sizeTostr(getuploadinfo.size);
          temp['name'] = initialState?.currentUser?.username;
          temp['upload_time'] = upload_time;
          resresults.push(temp);
          setvideo(resresults);
          setuploading(false);
          setdisable(false);
          console.log('成功'); // 这里是将拼接好的文件链接返回给后台
        }
      }
    };
    oReq.open('POST', url);
    // 在这里提交数据到oss
    oReq.send(oMyForm);
  }

  // 上传验证
  const beforeUpload = (file: RcFile) => {
    const filetype = file.type === 'video/mp4';
    if (!filetype) {
      message.error('只能上传mp4文件');
    }
    return filetype;
  };

  // 新增视频提交
  const add_video = async (value: any) => {
    console.log(value);
    let request_body = {
      ...value,
      //必填项
      video_name: videname,
      video_size: sizes,
      video_time: video_time,
      url: videourl,
      icon: imageUrl,
    };
    console.log(request_body);
    let res: any = await add_edit_video(request_body);
    console.log('新增视频', res);
    if (res.code === 200) {
      //刷新列表
      actionRef.current?.reload();
      message.success('添加成功');
      //关闭弹窗
      isShowAddVideoModal(false);
    } else {
      message.error(res.msg);
    }
  };

  // 视频文件列表字段
  const columns: ProColumns<GithubIssueItem>[] = [
    {
      title: '文件名称',
      hideInSearch: true,
      key: 'video_name',
      dataIndex: 'video_name',
    },
    {
      title: '视频时长',
      hideInSearch: true,
      key: 'video_times',
      dataIndex: 'video_times',
      render: (_, record) => {
        // console.log(record);
        var x = 0;
        if (record.video_times) {
          x = record.video_times;
        } else {
          if (video_time != 0) {
            x = video_time;
          } else {
            return;
          }
        }
        var d = moment.duration(x, 'seconds');
        var hours: any = Math.floor(d.asHours()).toString();
        var mins: any = (Math.floor(d.asMinutes()) - hours * 60).toString();
        var second = (Math.floor(d.asSeconds()) - mins * 60).toString();
        if (hours.toString().length == 1) {
          hours = '0' + hours;
        }
        if (mins.toString().length == 1) {
          mins = '0' + mins;
        }
        if (second.toString().length == 1) {
          second = '0' + second;
        }
        return hours + ':' + mins + ':' + second;
      },
    },
    {
      title: '文件大小',
      hideInSearch: true,
      key: 'size',
      dataIndex: 'size',
      render: (_, record) => {
        if (record.size) {
          let text = '';
          text += record.size + 'MB';
          return text;
        }
      },
    },
    {
      title: '上传人',
      hideInSearch: true,
      key: 'name',
      dataIndex: 'name',
    },
    {
      title: '上传时间',
      hideInSearch: true,
      key: 'upload_time',
      dataIndex: 'upload_time',
    },
    {
      title: '操作',
      hideInSearch: true,
      key: 'action',
      align: 'center',
      render: (_, record) => {
        // console.log(record);
        if (record.video_name) {
          return (
            <a key="Del" onClick={Delvideo}>
              删除
            </a>
          );
        } else {
          return (
            <Upload
              // loading={}
              name="head_img"
              className="avatar-uploader"
              beforeUpload={(info) => beforeUpload(info)}
              customRequest={(info) => send_request(info)}
              showUploadList={false}
            >
              <Button disabled={disable} loading={uploading} icon={<UploadOutlined />}>
                上传
              </Button>
            </Upload>
          );
        }
      },
    },
  ];
  return (
    <Modal
      title="新增视频"
      centered
      open={addVideoModal}
      onCancel={() => isShowAddVideoModal(false)}
      width={800}
      destroyOnClose={true}
      footer={null}
    >
      <Divider />
      <ProForm
        submitter={{
          searchConfig: {
            submitText: '提交',
            resetText: '取消',
          },
          resetButtonProps: {
            style: {
              // 隐藏重置按钮
              display: 'block',
              position: 'absolute',
              left: 'calc(50% - 107px)',
            },
          },
          submitButtonProps: {
            style: {
              display: 'block',
              position: 'absolute',
              right: 'calc(50% - 107px)',
            },
          },
        }}
        onReset={() => isShowAddVideoModal(false)}
        onFinish={(value) => add_video(value)}
      >
        <div>
          <ProFormGroup>
            <div style={{ display: 'flex', width: '280px' }}>
              <div className="ant-col ant-form-item-label" style={{ width: '80px' }}>
                <label className="ant-form-item-required" title="评估分类">
                  视频图片
                </label>
              </div>
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <AliyunOSSUpload imageUrl={imageUrl} setImageUrl={setimageUrl}></AliyunOSSUpload>
                <Button style={{ marginLeft: '20px' }} onClick={del}>
                  删除
                </Button>
              </div>
            </div>
            <ProFormText
              width={280}
              style={{ marginLeft: '15px' }}
              name="name"
              label="视频名称"
              placeholder="视频名称"
              rules={[
                {
                  required: true,
                  message: '请输入视频名称',
                },
                { pattern: /(^\S)((.)*\S)?(\S*$)/, message: '不能输入空格' },
              ]}
            />
            <ProFormSelect
              width={280}
              name="cate_type"
              label="评估分类"
              request={async () => [{ label: '脑卒中', value: 1 }]}
              rules={[
                {
                  required: true,
                  message: '请输入评估分类',
                },
              ]}
            />
            <ProFormSelect
              name="type"
              label="视频分类"
              width={280}
              request={async () => get_field('video_type')}
              rules={[
                {
                  required: true,
                  message: '请输入视频分类',
                },
              ]}
            />
            <ProFormText
              width={592}
              name="remark"
              label="备注"
              placeholder="请输入备注"
              rules={[
                {
                  max: 300,
                  message: '备注最多300 字符',
                  validateTrigger: 'onBlur',
                },
              ]}
              // initialValue={memberdata.remark}
            />
          </ProFormGroup>
        </div>

        <div className="ant-col ant-form-item-label" style={{ width: '100px' }}>
          <label className="ant-form-item-required" title="评估分类">
            视频文件
          </label>
        </div>
        <Table
          columns={columns}
          // actionRef={actionRef}
          dataSource={video}
          rowKey={(record) => (record.id ? record.id : 0)}
          pagination={false}
          style={{ paddingBottom: '20px' }}
        />
        <br />
      </ProForm>
      <br />
    </Modal>
  );
};
export default AddMyselfVideo;
